package com.moli.iov.task.remoting.op.reponse;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.moli.iov.cache.RedisUtil;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.task.constants.Constants;
import com.moli.iov.util.HttpUtil;
import com.moli.iov.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.util.Map;

/**
 * <p>
 *
 *  获取OP Token
 *
 * </p>
 *
 * @Auther: zql
 * @Date: 2019/1/7 13:44
 */
@Slf4j
@Component
public class TokenResponseHandler {

    @Autowired
    private RedisUtil redisUtil;

    @Value("${op_token_time}")
    private long opTokenTime;

    @Value("${op_username}")
    private String username;

    @Value("${op_password}")
    private String password;

    @Value("${op_user_type}")
    private String userType;

    @Value("${op_get_token_url}")
    private String opGetTokenUrl;

    @Value("${op_channel_val}")
    private String opChannelVal;

    /**
     * 获取凭证token
     * @return
     * @throws Exception
     */
    public String getToken() throws IOException {

        String token = redisUtil.get(Constants.TASK_SERVICE_OP_TOKEN);

        if (StringUtil.isBlank(token)) {
            return getTokenReal();
        }

        return token;
    }

    /**
     * 实际获取token的方法
     * @return
     */
    protected String getTokenReal() throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("account", Base64Utils.encodeToString(username.getBytes()));
        params.put("password", Base64Utils.encodeToString(password.getBytes()));
        params.put("user_type", userType);

        Map<String, String> header = Maps.newHashMap();
        header.put("channel", opChannelVal);
        String result = HttpUtil.postJson(opGetTokenUrl, JSONObject.toJSONString(params), header);
        if(StringUtil.isBlank(result)){
            throw new BusinessException("获取token失败，返回result空");
        }

        JSONObject resultObj = JSONObject.parseObject(result);

        if(Constants.OP_SUCCESS != resultObj.getInteger("code")){
            log.error("登陆失败，返回code不是200  入参：{}, 出参：{}", params, resultObj);
            throw new BusinessException("登陆失败，返回code不是200");
        }
        JSONObject data = resultObj.getJSONObject("data");
        if(data == null){
            log.error("登陆失败，返回data为空  入参：{}, 出参：{}", params, resultObj);
            throw new BusinessException("登陆失败，返回data为空");
        }

        String token = data.getString("token");
        if(StringUtil.isBlank(token)){
            log.error("登陆失败，返回token为空  入参：{}, 出参：{}", params, resultObj);
            throw new BusinessException("登陆失败，返回token为空");
        }
        redisUtil.set(Constants.TASK_SERVICE_OP_TOKEN, token, opTokenTime);
        return token;
    }

    /**
     *
     * 判断参数token是否过期
     * @return
     */
    public boolean tokenIsExpire() {
        return true;
    }
}
